import React, { useState, useEffect, use } from 'react';
import {
  Button,
  Table,
  Space,
  Popconfirm,
  message,
  Modal,
  Form,
  Input,
  Upload,
  Select
} from 'antd';
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  UploadOutlined
} from '@ant-design/icons';
import './CategoryManage.css';
import { useRequest } from 'ahooks';
import { getCategories, getProducts, updateCategories, deleteCategories } from '../../api/dashboard';

const { Option } = Select;

const CategoryManage = () => {
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  
  const userId = localStorage.getItem('adminUser').id ||1;
  const {runAsync:fetchCategories} = useRequest(getCategories, {
      manual:true
  })

  const {runAsync:fetchProducts} = useRequest(getProducts, {
      manual:true
  })

  const {runAsync:updateCate} = useRequest(updateCategories, {
    manual:true
  });

  const {runAsync:deleteCate} = useRequest(deleteCategories, {
    manual:true
  });

  const fetchData = async () => {

    const storedCategories = await fetchCategories({params:{id:userId}});
    setCategories(storedCategories);
  }

  // 获取分类数据
  useEffect(() => {
    setLoading(true);
    fetchData();
    setLoading(false);
  }, []);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 70
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 80,
      render: (icon) => <span style={{ fontSize: 24 }}>{icon}</span>
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      sorter: (a, b) => a.sort - b.sort
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 'active' ? '#52c41a' : '#ff4d4f' }}>
          {status === 'active' ? '启用' : '禁用'}
        </span>
      ),
      filters: [
        { text: '启用', value: 'active' },
        { text: '禁用', value: 'inactive' }
      ],
      onFilter: (value, record) => record.status === value
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 添加分类
  const handleAdd = () => {
    form.resetFields();
    setEditingId(null);
    setVisible(true);
  };

  // 编辑分类
  const handleEdit = (record) => {
    form.setFieldsValue({
      name: record.name,
      icon: record.icon,
      sort: record.sort,
      status: record.status,
    });
    setEditingId(record.id);
    setVisible(true);
  };

  // 删除分类
  const handleDelete = async (id) => {
    // 检查是否有商品使用该分类
    const products = await fetchProducts({params:{id:userId}});
    const hasProducts = products.some(product => product.categoryId === id);

    if (hasProducts) {
      message.error('该分类下还有商品，不能删除');
      return;
    }
    const updatedCategories = await deleteCate({params:{id:id}});
    setCategories(updatedCategories);
    
    message.success('分类删除成功');
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        setConfirmLoading(true);

        setTimeout(async () => {
          if (editingId) {
            // 更新分类
            const updatedCategories = await updateCate([{
              id: editingId,
              ...values,
            }])
            setCategories(updatedCategories);
            message.success('分类更新成功');
          } else {
            // 添加新分类
            const newCategory = {
              ...values,
              id: Date.now()
            };

            const updatedCategories = [...categories, newCategory];
            setCategories(updatedCategories);
            localStorage.setItem('categories', JSON.stringify(updatedCategories));
            message.success('分类添加成功');
          }
          setVisible(false);
          setConfirmLoading(false);
        }, 1000);
      })
      .catch(info => {
        console.log('验证失败:', info);
      });
  };

  // 处理模态框取消
  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <div className="category-manage">
      <div className="page-header">
        <h2>分类管理</h2>
        <div className="page-header-actions">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加分类
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={categories}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
      />

      <Modal
        title={editingId ? "编辑分类" : "添加分类"}
        open={visible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        confirmLoading={confirmLoading}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
          name="categoryForm"
          initialValues={{ status: 'active', sort: 0 }}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>

          <Form.Item
            name="icon"
            label="分类图标"
            rules={[{ required: true, message: '请输入分类图标' }]}
          >
            <Input placeholder="请输入分类图标，如 📱" />
          </Form.Item>

          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <Input type="number" placeholder="请输入排序值（数字越小越靠前）" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManage; 